import { compile } from 'json-schema-to-typescript';
import { readdirSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import $RefParser from '@apidevtools/json-schema-ref-parser';

const typesDir = join(__dirname, '../../shared/types');
const outputDir = join(__dirname, '../lib/types/generated');

// 获取所有 JSON 文件
const jsonFiles = readdirSync(typesDir).filter(file => file.endsWith('.json'));

// 为每个 JSON 文件生成类型定义
jsonFiles.forEach(async jsonFile => {
    const inputPath = join(typesDir, jsonFile);
    const outputPath = join(outputDir, jsonFile.replace('.json', '.ts'));
    
    console.log(`Generating types for ${jsonFile}...`);
    
    try {
        // 读取并解析 JSON schema，处理引用
        const parser = new $RefParser();
        const schema = await parser.dereference(inputPath);
        
        if (!schema.definitions) {
            throw new Error(`No definitions found in ${jsonFile}`);
        }
        
        // 生成所有定义的类型
        const types = await Promise.all(
            Object.entries(schema.definitions).map(async ([name, definition]) => {
                // 添加 JSDoc 注释
                const description = definition.description ? `/** ${definition.description} */\n` : '';
                
                // 生成类型定义
                const ts = await compile(definition as any, name, {
                    bannerComment: '',
                    style: {
                        singleQuote: true,
                        semi: true,
                        tabWidth: 2
                    },
                    unreachableDefinitions: true,
                    ignoreMinAndMaxItems: true,
                    maxItems: 20,
                    declareExternallyReferenced: false
                });
                
                // 添加 JSDoc 注释
                return description + ts;
            })
        );
        
        // 写入文件
        writeFileSync(outputPath, types.join('\n\n'));
        console.log(`Successfully generated types for ${jsonFile}`);
    } catch (error) {
        console.error(`Failed to generate types for ${jsonFile}:`, error);
    }
});

console.log('All type definitions have been generated!'); 